﻿using System;
using System.Globalization;
using System.Text;
using VisionarySystems.TimeRegi.View.WorkTimeCalculator;

namespace VisionarySystems.TimeRegi.View
{
	public class WorkTimeOverviewGenerator
	{
		private readonly IWorkTimeCalculator m_WorkTimeCalculator;

		public WorkTimeOverviewGenerator(IWorkTimeCalculator WorkTimeCalculator)
		{
			m_WorkTimeCalculator = WorkTimeCalculator;
		}

		public string GenerateOverview()
		{
			const int MINIMUM_DAYS_INCLUDED = 30;
			TimeSpan totalFullWeeks = new TimeSpan();
			StringBuilder result = new StringBuilder();

			int fullWeeksShown = 0;

			DayOfWeek startDay = DateTime.Now.Date.AddDays(-1 * MINIMUM_DAYS_INCLUDED).DayOfWeek;
			int startDayNo = (int)startDay;
			if (startDayNo == 0) startDayNo = 7;
			DateTime startDate = DateTime.Now.Date.AddDays(-1 * MINIMUM_DAYS_INCLUDED).AddDays(-1 * (startDayNo - 1));

			for (DateTime dateNo = startDate; dateNo < DateTime.Now.Date; dateNo = dateNo.AddDays(1))
			{
				if (dateNo.DayOfWeek == DayOfWeek.Monday)
					result.Append(string.Format("Uge {0}: \r\n", GetWeekNumber(dateNo)));

				TimeSpan workedDate = m_WorkTimeCalculator.GetTime(dateNo, dateNo.AddDays(1).AddSeconds(-1), true);
				result.Append(string.Format("{0}: {1:D2}:{2:D2}\r\n", dateNo.DayOfWeek, (int)workedDate.TotalHours, workedDate.Minutes));
				if (dateNo.DayOfWeek == DayOfWeek.Sunday)
				{
					TimeSpan workedWeek = m_WorkTimeCalculator.GetTime(dateNo.AddDays(-7), dateNo, true);
					result.Append(string.Format("Total: {0:D2}:{1:D2}\r\n\r\n", (int)workedWeek.TotalHours, workedWeek.Minutes));
					totalFullWeeks += workedWeek;
					fullWeeksShown++;
				}
			}
			long TotalTicks = (long)(totalFullWeeks.Ticks / fullWeeksShown);
			TimeSpan AverageTime = new TimeSpan(TotalTicks);
			result.Append(string.Format("Gennemsnit for hele uger: {0:D2}:{1:D2}\r\n\r\n", (int)AverageTime.TotalHours, AverageTime.Minutes));
			return result.ToString();
		}

		private int GetWeekNumber(DateTime dtPassed)
		{
			CultureInfo ciCurr = CultureInfo.CurrentCulture;
			int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
			return weekNum;
		}

	}
}